<template>
  <div class="profile-container">
    <div class="profile-header">
      <h2>个人中心</h2>
      <el-button type="danger" @click="handleLogout">退出登录</el-button>
    </div>
    
    <el-card class="profile-card">
      <!-- 基本信息 -->
      <div class="section">
        <h3>基本信息</h3>
        <el-form :model="userInfo" label-width="100px">
          <el-form-item label="用户名">
            <el-input v-model="userInfo.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="userInfo.email" disabled></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateProfile">保存修改</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 头像上传 -->
      <div class="section">
        <h3>头像设置</h3>
        <div class="avatar-uploader">
          <el-upload
            action="/api/upload/avatar"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :before-upload="beforeAvatarUpload"
            accept="image/jpeg,image/png,image/gif"
            :headers="uploadHeaders">
            <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </div>
      </div>

      <!-- 密码修改 -->
      <div class="section">
        <h3>修改密码</h3>
        <el-form :model="passwordForm" label-width="100px" :rules="rules" ref="passwordForm">
          <el-form-item label="原密码" prop="oldPassword">
            <el-input type="password" v-model="passwordForm.oldPassword"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input type="password" v-model="passwordForm.newPassword"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="changePassword">修改密码</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 虚拟币信息 -->
      <div class="section">
        <h3>虚拟币账户</h3>
        <div class="currency-info">
          <div class="balance-box">
            <div class="balance-label">当前余额</div>
            <div class="balance-amount">{{ virtualCurrency.balance }}</div>
            <el-button type="primary" @click="showRechargeDialog">充值</el-button>
          </div>
        </div>

        <!-- 充值记录 -->
        <div class="sub-section">
          <h4>充值记录</h4>
          <el-table :data="rechargeRecords" style="width: 100%">
            <el-table-column prop="time" label="充值时间" width="180"></el-table-column>
            <el-table-column prop="amount" label="充值金额" width="120"></el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'success' ? 'success' : 'warning'">
                  {{ scope.row.status === 'success' ? '成功' : '处理中' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="orderNo" label="订单号"></el-table-column>
          </el-table>
        </div>

        <!-- 消费明细 -->
        <div class="sub-section">
          <h4>消费明细</h4>
          <el-table :data="consumptionRecords" style="width: 100%">
            <el-table-column prop="time" label="消费时间" width="180"></el-table-column>
            <el-table-column prop="amount" label="消费金额" width="120"></el-table-column>
            <el-table-column prop="type" label="类型" width="120"></el-table-column>
            <el-table-column prop="description" label="说明"></el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 登录记录 -->
      <div class="section">
        <h3>登录记录</h3>
        <el-table :data="loginLogs" style="width: 100%">
          <el-table-column prop="time" label="登录时间"></el-table-column>
          <el-table-column prop="ip" label="IP地址"></el-table-column>
          <el-table-column prop="device" label="设备信息"></el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 充值对话框 -->
    <el-dialog
      title="虚拟币充值"
      v-model="rechargeDialogVisible"
      width="400px">
      <el-form :model="rechargeForm" label-width="100px" :rules="rechargeRules" ref="rechargeForm">
        <el-form-item label="充值金额" prop="amount">
          <el-input-number v-model="rechargeForm.amount" :min="1" :max="10000"></el-input-number>
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-radio-group v-model="rechargeForm.paymentMethod">
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="wechat">微信支付</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rechargeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRecharge">确认充值</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'UserProfile',
  components: {
    Plus
  },
  data() {
    return {
      userInfo: {
        username: '',
        email: '',
        avatar: ''
      },
      passwordForm: {
        oldPassword: '',
        newPassword: ''
      },
      rules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ]
      },
      loginLogs: [],
      // 虚拟币相关数据
      virtualCurrency: {
        balance: 0
      },
      rechargeRecords: [],
      consumptionRecords: [],
      // 充值对话框相关
      rechargeDialogVisible: false,
      rechargeForm: {
        amount: 10,
        paymentMethod: 'alipay'
      },
      rechargeRules: {
        amount: [
          { required: true, message: '请输入充值金额', trigger: 'blur' }
        ],
        paymentMethod: [
          { required: true, message: '请选择支付方式', trigger: 'change' }
        ]
      },
      // 上传相关
      uploadHeaders: {
        Authorization: `Bearer ${localStorage.getItem('token') || ''}`
      },
      loading: {
        userInfo: false,
        virtualCurrency: false,
        recharge: false
      }
    }
  },
  methods: {
    handleLogout() {
      ElMessageBox.confirm('确认退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 清除用户token
        localStorage.removeItem('token');
        // 清除其他可能的用户状态
        localStorage.removeItem('userInfo');
        // 跳转到登录页
        this.$router.push('/login');
        ElMessage.success('已成功退出登录');
      }).catch(() => {
        // 取消退出
      });
    },
    updateProfile() {
      // 调用API更新用户信息
      console.log('更新用户信息:', this.userInfo);
    },
    handleAvatarSuccess(res) {
      if (res.code === 0) {
        this.userInfo.avatar = res.data.url;
        ElMessage.success('头像上传成功');
      } else {
        ElMessage.error(res.message || '上传失败');
      }
    },
    handleAvatarError(err) {
      console.error('上传失败:', err);
      ElMessage.error('头像上传失败，请重试');
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        ElMessage.error('上传头像图片只能是图片格式!');
        return false;
      }
      if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    changePassword() {
      this.$refs.passwordForm.validate((valid) => {
        if (valid) {
          // 调用API修改密码
          console.log('修改密码:', this.passwordForm);
        }
      });
    },
    async fetchUserInfo() {
      this.loading.userInfo = true;
      try {
        const response = await request.get('/users/me');
        if (response.data.code === 0) {
          const userData = response.data.data;
          this.userInfo = {
            username: userData.username || '',
            email: userData.email || '',
            avatar: userData.avatar || ''
          };
          // 更新虚拟币余额
          this.virtualCurrency.balance = userData.virtualCoins || 0;
        } else {
          ElMessage.error('获取用户信息失败');
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        ElMessage.error('获取用户信息失败，请重试');
      } finally {
        this.loading.userInfo = false;
      }
    },
    // 显示充值对话框
    showRechargeDialog() {
      this.rechargeDialogVisible = true;
    },
    // 处理充值
    handleRecharge() {
      if (this.$refs.rechargeForm) {
        this.$refs.rechargeForm.validate(async (valid) => {
          if (valid) {
            this.loading.recharge = true;
            try {
              // TODO: 调用充值API
              ElMessage.success(`充值${this.rechargeForm.amount}元成功`);
              this.rechargeDialogVisible = false;
              // 刷新虚拟币数据
              await this.getVirtualCurrencyData();
            } catch (error) {
              console.error('充值失败:', error);
              ElMessage.error('充值失败，请重试');
            } finally {
              this.loading.recharge = false;
            }
          }
        });
      }
    },
    // 获取虚拟币数据
    async getVirtualCurrencyData() {
      this.loading.virtualCurrency = true;
      try {
        // 获取用户虚拟币余额
        const userResponse = await request.get('/users/me');
        if (userResponse.data.code === 0) {
          const userData = userResponse.data.data;
          this.virtualCurrency.balance = userData.virtualCoins || 0;
        }
        
        // 获取充值记录
        const rechargeResponse = await request.get('/payment/recharge-records');
        if (rechargeResponse.data.code === 0) {
          this.rechargeRecords = rechargeResponse.data.data.map(record => ({
            time: new Date(record.createdAt).toLocaleString(),
            amount: record.amount,
            status: record.status === 'completed' ? 'success' : 'pending',
            orderNo: record._id
          }));
        }
        
        // 获取消费记录
        const consumptionResponse = await request.get('/payment/consumption-records');
        if (consumptionResponse.data.code === 0) {
          this.consumptionRecords = consumptionResponse.data.data.map(record => ({
            time: new Date(record.createdAt).toLocaleString(),
            amount: record.amount,
            type: record.type,
            description: record.description
          }));
        }
      } catch (error) {
        console.error('获取虚拟币数据失败:', error);
        ElMessage.error('获取虚拟币数据失败，请重试');
      } finally {
        this.loading.virtualCurrency = false;
      }
    }
  },
  mounted() {
    this.fetchUserInfo();
    this.getVirtualCurrencyData();
  }
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
}
.profile-card {
  margin-top: 20px;
}
.section {
  margin-bottom: 30px;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  transition: all 0.3s;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.profile-header h2 {
  margin: 0;
}

/* 虚拟币相关样式 */
.currency-info {
  display: flex;
  align-items: center;
  margin: 20px 0;
}
.balance-box {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  padding: 15px 20px;
  border-radius: 8px;
  margin-right: 20px;
}
.balance-label {
  font-size: 16px;
  color: #606266;
  margin-right: 15px;
}
.balance-amount {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-right: 20px;
}
.sub-section {
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>